package engine.scheduler.jobs.impl.quartz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.springframework.scheduling.quartz.QuartzJobBean;

import engine.Consts;
import engine.dataobjects.MailItemInstance;
import engine.scheduler.jobs.IMailItemJob;
import engine.scheduler.jobs.IMailItemJobDetail;
import engine.services.IDataResource;

/***
 * Job that runs to update the configuration data in case
 * changes have been made to the xml file
 * 
 * @author IlanaP
 *
 */
public class ConfigurationUpdateJob extends QuartzJobBean {

	private static Log log = LogFactory.getLog(ConfigurationUpdateJob.class);

	

	@Override
	public void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
			myExecuteInternal(arg0.getJobDetail().getJobDataMap(), arg0.getScheduler());
			log.info("next run is at: " + arg0.getNextFireTime());			
	}
	
	private MailItemJob addJob(Scheduler scheduler, IMailItemJobDetail jobDetails, Trigger defaultTrigger ) {
		MailItemJob job = new MailItemJob();
		job.setScheduler(scheduler);
		job.setDefaultTrigger(defaultTrigger);
		job.init(jobDetails, false);
		return job;
	}

	@SuppressWarnings("unused")
	void myExecuteInternal(JobDataMap map, Scheduler scheduler) {
		IDataResource configResource = (IDataResource)map.get("configResource");
		IMailItemJobDetail jobDetails = (IMailItemJobDetail)map.get("defaultJobDetails");
		Trigger defaultTrigger = (Trigger)map.get("defaultTrigger");
		
		log.info("executing ConfigurationUpdateJob");
		try {
			// pause the scheduler
			log.info("Pausing scheduler");
			scheduler.pauseJobGroup(Consts.MESSAGE_JOB_GROUP);
			
			// removing all the running jobs
			String[] jobNames = scheduler.getJobNames(Consts.MESSAGE_JOB_GROUP);
			List<String> jobNamesList = new ArrayList<>();// Arrays.asList(jobNames);
			for (String jobName : jobNames) {
				scheduler.deleteJob(jobName, Consts.MESSAGE_JOB_GROUP);
			}
			
			// get all the mail items refreshed from the datasource
			configResource.refresh();
			
			Map<IMailItemJob, IMailItemJobDetail> updatedJobs = new HashMap<>();
			List<MailItemInstance> items = configResource.getActiveMailItemInstances();
			for (MailItemInstance item : items) {
				log.info("New job Id: " + MailItemJobDetail.getNameForItem(item));
				jobDetails.setItem(item);
				addJob(scheduler, jobDetails, defaultTrigger);
			}
			
			// restart the scheduler
			log.info("Resuming scheduler");
			scheduler.resumeJobGroup(Consts.MESSAGE_JOB_GROUP);

		} catch (Exception e) {
			log.error(e);
		}
		log.info("done executing ConfigurationUpdateJob");
		
	}

}
